package com.powernode.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.vo.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 退出的handler
 */
@Component
public class AppLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 用户点击退出后会执行 security该handler
     *
     * 退出成功后，删除redis中的token
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        Result result = new Result(200, "退出成功");

        String jsonStr = objectMapper.writeValueAsString(result);
        response.getWriter().write(jsonStr);
    }
}
